<script lang="ts" setup>
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  User,
  Lock,
  Key,
  Avatar,
  TrendCharts,
  SwitchButton,
  House,
  ShoppingCart,
  Star,
  Money,
  Warning,
  FirstAidKit,
  Present,
  Coffee,
  Delete
} from '@element-plus/icons-vue'
import { ref, onMounted, defineComponent, h } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElSubMenu, ElMenuItem, ElIcon } from 'element-plus'
import { apiRequest } from '../utils/request'

const router = useRouter()
const userInfo = ref<any>(null)
const menus = ref<any[]>([])

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

// 获取用户信息
const getUserInfo = () => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    userInfo.value = JSON.parse(userInfoStr)
  }
}

// 获取动态菜单
const getMenus = async () => {
  try {
    const res = await apiRequest({
      url: '/api/Permissions/GetUserMenus/user-menus',
      method: 'get',
      serviceName: 'auth'
    })
    // 只保留有Name和Path的菜单
    menus.value = Array.isArray(res.data) ? res.data : []
  } catch (e) {
    menus.value = []
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 清除本地存储
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')

    ElMessage.success('已退出登录')

    // 跳转到登录页面
    router.push('/login')
  } catch {
    // 用户取消退出
  }
}

const iconMap: Record<string, any> = {
  // 基础功能
  '首页': TrendCharts,
  '个人信息': TrendCharts,
  '羊场首页': House,
  
  // 权限管理
  '权限中心': Key,
  '权限管理': Key,
  '权限分配': Key,
  '角色设置': User,
  '角色管理': User,
  '用户管理': Avatar,
  '人员管理': Avatar,
  
  // 基础信息
  '基础信息': Setting,
  '羊场管理': House,
  '栋舍管理': House,
  
  // 生产管理
  '生产管理': Setting,
  '羊只采购': ShoppingCart,
  '母羊配种': Star,
  '羊只销售': Money,
  '羊只死亡': Warning,
  '种母妊检': FirstAidKit,
  '种母分娩': Present,
  '种母断奶': Coffee,
  '淘汰管理': Delete,
  
  // 羊只管理
  '羊只管理': House,
  '羊只档案': Document,
  '羊只信息': Document,
  
  // 其他功能
  '系统管理': Setting,
  '数据统计': TrendCharts,
  '报表管理': Document,
  '设置': Setting,
  '配置': Setting,
  '管理': Setting,
  '信息': Document,
  '档案': Document,
  '记录': Document,
  '统计': TrendCharts,
  '分析': TrendCharts,
  '报表': Document,
  '采购': ShoppingCart,
  '销售': Money,
  '配种': Star,
  '分娩': Present,
  '断奶': Coffee,
  '死亡': Warning,
  '淘汰': Delete,
  '妊检': FirstAidKit,
  '用户': User,
  '角色': User,
  '权限': Key,
  '栋舍': House,
  '羊场': House,
  '羊只': House,
  '母羊': Star,
  '种母': Star,
  
  // 更多业务相关图标
  'EweMatingList': Star,
  'SheepSale': Money,
  'SheepDeath': Warning,
  'EwePregnancyCheck': FirstAidKit,
  'EweLambing': Present,
  'EweWeaning': Coffee,
  'EliminationManagement': Delete,
  'PurchaseView': ShoppingCart,
  'UserinfoList': Avatar,
  'RolesList': User,
  'Permissiondisplay': Key,
  'SheepFiles': Document,
  'ColumnManagement': House,
  
  // 英文路径映射
  'Purchase': ShoppingCart,
  'Sale': Money,
  'Death': Warning,
  'Pregnancy': FirstAidKit,
  'Lambing': Present,
  'Weaning': Coffee,
  'Elimination': Delete,
  'User': Avatar,
  'Role': User,
  'Permission': Key,
  'File': Document,
  'Column': House,
  'Management': Setting,
  'List': Document,
  'Add': Document,
  'Edit': Document,
  'Delete': Delete,
  'View': Document,
  'Detail': Document,
}

// 新增递归菜单组件
const MenuTree = defineComponent({
  name: 'MenuTree',
  props: {
    menus: {
      type: Array as () => Array<any>,
      required: true
    }
  },
  setup(props) {
    // 智能图标选择函数
    const getSmartIcon = (menuName: string) => {
      // 首先尝试精确匹配
      if (iconMap[menuName]) {
        return iconMap[menuName]
      }
      
      // 然后尝试关键词匹配（按长度降序，优先匹配更长的关键词）
      const keywords = Object.keys(iconMap).sort((a, b) => b.length - a.length)
      for (const keyword of keywords) {
        if (menuName.includes(keyword)) {
          return iconMap[keyword]
        }
      }
      
      // 尝试英文路径匹配
      const pathKeywords = ['Purchase', 'Sale', 'Death', 'Pregnancy', 'Lambing', 'Weaning', 'Elimination', 'User', 'Role', 'Permission', 'File', 'Column', 'Management', 'List', 'Add', 'Edit', 'Delete', 'View', 'Detail']
      for (const keyword of pathKeywords) {
        if (menuName.includes(keyword)) {
          return iconMap[keyword]
        }
      }
      
      // 最后返回默认图标
      return IconMenu
    }
    
    return () => props.menus.map((item: any) => {
      // 智能选择图标
      const iconComp = getSmartIcon(item.Name)
      
      // 开发模式下显示图标匹配信息
      if (import.meta.env.DEV) {
        console.log(`菜单项: ${item.Name} -> 图标: ${iconComp.name}`)
      }
      if (item.Children && item.Children.length > 0) {
        return h(
          ElSubMenu,
          { index: String(item.Id) },
          {
            title: () => [h(ElIcon, {}, () => h(iconComp)), h('span', {}, item.Name)],
            default: () => h(MenuTree, { menus: item.Children })
          }
        )
      } else if (item.Path && item.Path !== '//') {
        return h(
          ElMenuItem,
          { index: item.Path },
          [h(ElIcon, {}, () => h(iconComp)), h('span', {}, item.Name)]
        )
      } else if (item.Path === '//' && (!item.Children || item.Children.length === 0)) {
        return h(
          ElSubMenu,
          { index: String(item.Id), disabled: true },
          {
            title: () => [h(ElIcon, {}, () => h(iconComp)), h('span', {}, item.Name)]
          }
        )
      }
      return null
    })
  }
})

onMounted(() => {
  getUserInfo()
  getMenus()
})
</script>

<template>
  <div class="app-container">
    <el-container class="main-container">
      <!-- 头部导航 -->
      <el-header class="app-header">
        <div class="header-content">
          <div class="header-left">
            <div class="logo-section new-logo">
              <el-icon class="logo-icon new-logo-icon">
                <House />
              </el-icon>
              <span class="logo-text new-logo-text">智慧农业-智慧畜牧育种管理平台</span>
            </div>
          </div>
          <div class="header-right">
            <div class="user-info">
              <el-avatar :size="32" class="user-avatar">
                <el-icon>
                  <User />
                </el-icon>
              </el-avatar>
              <span class="welcome-text">欢迎您，{{ userInfo?.UserName || '用户' }}</span>
              <el-button type="danger" size="small" class="logout-btn" @click="handleLogout">
                <el-icon>
                  <SwitchButton />
                </el-icon>
                退出登录
              </el-button>
            </div>
          </div>
        </div>
      </el-header>

      <el-container class="content-container">
        <!-- 侧边栏 -->
        <el-aside width="260px" class="app-sidebar">
          <el-menu :default-active="$route.path" router class="sidebar-menu" @open="handleOpen" @close="handleClose"
            background-color="#001529" text-color="#fff" active-text-color="#409EFF">

            <!-- 首页菜单项 -->
            <div class="sidebar-top-btns">
              <div class="sidebar-card-btn" :class="{'active': $route.path === '/home' || $route.path === '/'}" @click="$router.push('/home')">
                <div class="card-btn-content">
                  <el-icon><TrendCharts /></el-icon>
                  <span>个人信息</span>
                </div>
              </div>
              <div class="sidebar-card-btn" :class="{'active': $route.path === '/FarmHomeView'}" @click="$router.push('/FarmHomeView')">
                <div class="card-btn-content">
                  <el-icon><House /></el-icon>
                  <span>羊场首页</span>
                </div>
              </div>
            </div>

            <!-- 动态菜单递归渲染 -->
            <MenuTree :menus="menus" />

          </el-menu>
        </el-aside>

        <!-- 主内容区域 -->
        <el-main class="app-main">
          <div class="main-content">
            <RouterView />
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
.app-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.main-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.content-container {
  flex: 1;
  display: flex;
  min-height: 0;
}

/* 头部样式 */
.app-header {
  background: linear-gradient(90deg, #1a1a1a 0%, #2d2d2d 100%);
  color: white;
  height: 70px !important;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  position: relative;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 24px;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 28px;
  color: #409EFF;
}

.logo-text {
  font-size: 24px;
  font-weight: 600;
  background: linear-gradient(45deg, #409EFF, #67C23A);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  backdrop-filter: blur(10px);
}

.user-avatar {
  background: linear-gradient(45deg, #409EFF, #67C23A);
}

.welcome-text {
  font-size: 14px;
  color: #e0e0e0;
  white-space: nowrap;
}

.logout-btn {
  background: rgba(245, 108, 108, 0.8);
  border: none;
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.logout-btn:hover {
  background: rgba(245, 108, 108, 1);
  transform: translateY(-1px);
}

.logout-btn .el-icon {
  font-size: 12px;
}

/* 侧边栏样式优化为卡片渐变风格 */
.app-sidebar {
  background: #001529;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
  padding-top: 12px;
  height: 100%;
  position: sticky;
  top: 0;
  left: 0;
  z-index: 100;
}

.sidebar-menu {
  border: none;
  height: 100%;
  background: transparent;
}

.el-menu-item, .el-sub-menu__title {
  border-radius: 18px !important;
  margin: 10px 12px !important;
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 16px;
  background: linear-gradient(90deg, #4fc3f7 0%, #67C23A 100%);
  color: #fff !important;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.10);
  transition: background 0.2s, color 0.2s, box-shadow 0.2s;
  padding: 14px 24px !important;
}

.el-menu-item.is-active, .el-menu-item:focus, .el-menu-item:hover {
  background: linear-gradient(90deg, #409EFF 60%, #67C23A 100%) !important;
  color: #fff !important;
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.18);
}

.el-sub-menu__title {
  background: linear-gradient(90deg, #4fc3f7 0%, #67C23A 100%);
  color: #fff !important;
  font-size: 18px;
  font-weight: bold;
  margin-top: 12px;
  margin-bottom: 2px;
  opacity: 1 !important;
}

.el-sub-menu__title:hover {
  background: linear-gradient(90deg, #409EFF 60%, #67C23A 100%) !important;
  color: #fff !important;
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.18);
}

.el-sub-menu.is-disabled > .el-sub-menu__title {
  color: #e0e0e0 !important;
  opacity: 0.7 !important;
  background: linear-gradient(90deg, #bfcbd9 0%, #c3cfe2 100%) !important;
  font-weight: bold;
}

.el-menu-item .el-icon, .el-sub-menu__title .el-icon {
  font-size: 26px !important;
  margin-right: 12px;
}

.dashboard-item {
  background: linear-gradient(45deg, #409EFF, #67C23A);
  margin: 12px;
  border-radius: 18px;
  color: white !important;
  font-size: 20px;
  font-weight: bold;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15);
  padding: 18px 28px !important;
}

.dashboard-item:hover, .dashboard-item.is-active {
  background: linear-gradient(45deg, #66b1ff, #85ce61) !important;
  color: #fff !important;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.18);
}

/* 主内容区域样式 */
.app-main {
  background: #f5f7fa;
  padding: 0;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  height: 100%;
  padding: 24px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-sidebar {
    width: 200px !important;
  }

  .header-content {
    padding: 0 16px;
  }

  .logo-text {
    font-size: 20px;
  }

  .main-content {
    padding: 16px;
  }

  .user-info {
    flex-direction: column;
    gap: 8px;
    padding: 12px;
  }

  .welcome-text {
    font-size: 12px;
  }

  .logout-btn {
    font-size: 11px;
    padding: 4px 8px;
  }
}

/* 滚动条样式 */
.main-content::-webkit-scrollbar {
  width: 6px;
}

.main-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.main-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.main-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.sidebar-top-btns {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 16px 0 18px 0;
  margin-bottom: 8px;
}
.sidebar-card-btn {
  width: 95%;
  min-width: 150px;
  max-width: 220px;
  height: 38px;
  border-radius: 18px;
  background: #001529;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0 auto;
  position: relative;
  border: 1px solid #2a2a2a;
}
.sidebar-card-btn .card-btn-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  height: 100%;
}
.sidebar-card-btn .el-icon {
  font-size: 16px;
  color: #fff;
}
.sidebar-card-btn span {
  font-size: 13px;
  font-weight: 500;
  color: #fff;
  letter-spacing: 0.5px;
}
.sidebar-card-btn:hover {
  background: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  border: 1px solid #409EFF;
  transform: translateY(-1px);
  z-index: 2;
}

.sidebar-card-btn.active {
  background: #001529;
  border: 1px solid #2a2a2a;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.sidebar-card-btn.active .el-icon,
.sidebar-card-btn.active span {
  color: #409EFF;
}
</style>

<style scoped>
.new-logo {
  /* background: #656a73; */
  background: transparent;
  padding: 0 32px;
  height: 56px;
  display: flex;
  align-items: center;
  border-radius: 0 0 8px 0;
}
.new-logo-icon {
  font-size: 38px !important;
  color: #fff !important;
  margin-right: 16px;
}
.new-logo-text {
  color: #fff;
  font-size: 2rem;
  font-weight: bold;
  letter-spacing: 2px;
}
</style>

<style>
html, body {
  height: 100%;
  overflow: hidden;
}
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}
#app {
  height: 100%;
}
</style>
